package com.tvunetworks.center.device.schedule;

import com.alibaba.fastjson.JSONObject;
import com.tvunetworks.center.common.model.ps.PSR;
import com.tvunetworks.center.common.model.ps.PST;
import com.tvunetworks.center.device.model.PtsPrs;
import com.tvunetworks.center.device.util.MemcacheUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @program: tvucc-device
 * @description: SyncPSSchedule
 * @author lebronchen
 * @create: 2019-03-14 22:25
 **/

@Slf4j
@Service
@Component
@Lazy(false)
@Data
public class SyncPSSchedule {


    @Autowired
    @Qualifier("psMemcacheClient")
    private MemcachedClient psMemcacheClient;
    @Autowired
    private MemcacheUtil memcacheUtil;

    @Value("${psrSize}")
    private int psrSize;
    @Value("${pstSize}")
    private int pstSize;
    @Value("${timer.syncPSSchedule}")
    private long timer;

    /**
     *  syncPSSchedule
     */
    @Scheduled(initialDelay = 3000, fixedDelayString = "${timer.syncPSSchedule}")
    public void  syncPSSchedule(){
        log.error("fixedDelayString====："+timer);
        log.error(" psrSize:" + psrSize + ",pstSize" + pstSize);
        log.error("prs psrSize:"+JSONObject.toJSONString(PtsPrs.getPrs().size())+", pts pstSize"+JSONObject.toJSONString(PtsPrs.getPts().size()));
        try{
            Map<String, PSR> tempPrs = (Map<String, PSR>) memcacheGetMapVals("r_basic_info_", "allRPeerID", psrSize);
            if (tempPrs != null && tempPrs.size() > 0) {
                PtsPrs.setPrs(tempPrs);
            }else {
                log.error("syncPSScheduleTTTTTT>>>>>>>>>peerService PSR data is empty");
            }
        } catch (Exception e) {
            log.error("syncPSSchedule>>>>>>>>>sync PSR Exception,time:[{}],e:[{}]", System.currentTimeMillis(), e);
        }
        try{
            Map<String, PST> tempPts = (Map<String, PST>) memcacheGetMapVals("t_basic_info_", "allTPeerID", pstSize);
            if (tempPts != null && tempPts.size() > 0) {
                PtsPrs.setPts(tempPts);
            }else {
                log.error("syncPSScheduleTTTTTT>>>>>>>>>peerService PST data is empty");
            }
        } catch (Exception e) {
            log.error("syncPSSchedule>>>>>>>>>sync PST Exception,time:[{}],e:[{}]", System.currentTimeMillis(), e);
        }
    }

    private Object memcacheGetMapVals(String perStr, String perPeerFlag, int size) {
        if(psMemcacheClient ==null){
            log.error("====psMemcacheClient Is null======");
        }
        Map<String, Object> returnVals = null;
        try {
            returnVals = new HashMap<>(size);
            log.error(perPeerFlag+"=====Start====");
//            log.error("psMemcacheClient"+JSONObject.toJSONString(psMemcacheClient));
            //getAllpeerIDs
            if (psMemcacheClient!=null) {

                Set<String> allPeerIDs = (Set<String>) psMemcacheClient.get(perPeerFlag);

           //    log.error("====allPeerIDs======"+JSONObject.toJSONString(allPeerIDs));
                //get peer info
                if (allPeerIDs != null && allPeerIDs.size() > 0) {

                    Set<String> finalKeys = new HashSet<String>();
                    for (String peerID : allPeerIDs) {
                        finalKeys.add(perStr + peerID);
                    }
//                log.error("==finalKeys==="+JSONObject.toJSONString(finalKeys));
                    Map<String, Object> values = memcacheUtil.multiGet(psMemcacheClient, finalKeys);
                    //            Map<String, Object> values = psMemcacheClient.getBulk(finalKeys);
//                log.error("==memcacheUtil.multiGet==="+JSONObject.toJSONString(values));
                    if (values != null && values.size() > 0) {
                        for (Map.Entry<String, Object> entry : values.entrySet()) {
                            returnVals.put(entry.getKey().split(perStr)[1], entry.getValue());
                        }
                    }
                }
            }
//            log.error("==returnVals==="+JSONObject.toJSONString(returnVals));
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
            log.error("==memcacheGetMapVals Exception===",e);
        }
        return returnVals;
    }
}
